const {UserAndRole, User, Role} = require('../db/model/index')
const {Op} = require('sequelize')

const createUserAndRole = async ({uid, rid}) => {
  const result = await UserAndRole.create({
    uid,
    rid
  })

  const data = result.dataValues

  return data
}

const getUserAndRoleOne = async (id) => {
  const result = await UserAndRole.findOne({
    where: {
      id
    },
    include: [
      {
        model: User,
        attributes: {
          exclude: [ 'id', 'password' ]
        }
      },
      {
        model: Role,
        attributes: {
          exclude: [ 'id' ]
        }
      }
    ]
  })

  return result ? result.dataValues : result
}

const getUserAndRoleList = async ({userName, roleName, pageIndex, pageSize}) => {
  const result = await UserAndRole.findAndCountAll({
    limit: +pageSize,
    offset: pageSize * pageIndex,
    order: [
      [ 'id', 'desc' ]
    ],
    include: [
      {
        model: User,
        attributes: {
          exclude: [ 'id', 'password' ]
        },
        where: {
          nickName: {
            [Op.substring]: userName
          }
        }
      },
      {
        model: Role,
        attributes: {
          exclude: [ 'id' ]
        },
        where: {
          name: {
            [Op.substring]: roleName
          }
        }
      }
    ]
  })

  return {
    count: result.count,
    data: result.rows
  }
}

const updateUserAndRole = async ({rid, id}) => {
  const whereOpt = {
    id
  }
  const result = await UserAndRole.update({
    rid
  }, {
    where: whereOpt
  })

  const data = result.length > 0

  return data
}

module.exports = {
  createUserAndRole,
  getUserAndRoleList,
  getUserAndRoleOne,
  updateUserAndRole
}
